<?php
/**
 *  员工登录
*/

namespace app\admin\service;

use app\facade\Basic;
use app\admin\model\Operator;
use think\facade\Config;
use think\facade\Cache;

class Login extends BaseService
{

    /**
     *  用户登录
     * @var string
    */
    public function account($param){

//        if( !Captcha::check($param['verify'])) {
//            return Basic::data(1,'验证码错误');
//        }

        $where = [];
        /* 判断邮箱 */
        if(filter_var($param['account'],FILTER_VALIDATE_EMAIL)){
           $where['email'] =  $param['account'];
        } else {
            /* 判断手机号 */
            if (preg_match("/^1[34578]{1}\d{9}$/",$param['account'])) {
                $where['phone'] = $param['account'];
            } else {
                // 用户名登录
                $where['cname'] = $param['account'];
            }
        }

        $result = Operator::where($where)->where('is_del','0')->find();

        if(!$result){
            return Basic::data(1,'用户不存在');
        }

        if($result->status  != 1){
            return Basic::data(1,'账号被锁定');
        }

        /* 密码验证 */
        $password_salt = Config::get('operator.password_salt');
        $create_time = $result->create_time;
        $password = $param['password'];
        if($result->password !=  md5(md5($password.$password_salt.$create_time))){
            return Basic::data(1,'密码错误');
        }

        /* 保存登录信息 */
        $token = new Token();
        $token = $token->get($result);

        /* 更新登陆信息 */
        $result->login_num = ($result->login_num + 1);
        $result->last_login_time = date("Y-m-d H:i:s",time());
        $result->last_ip = $param['ip'];
        $result->save();

        $userinfo =[
            'username' => $result->cname,
            'isadmin' => $result->isadmin,
            'role' => $result->roles,
            'id' => $result->id,
            'token' => $token
        ];
        $this->logger->logOperation($result->id,'login','登录','登录系统');


        return Basic::data(0,'登录成功',$userinfo);
    }

    /**
     *  退出系统
    */
    public function logout($param){
        if(Cache::delete($param['token'])){
            return Basic::data(0,'退出成功');
        } else {
            return Basic::data(1,'退出失败');
        }
    }
}
